from django.http import JsonResponse
from django.views.decorators.http import require_GET, require_POST
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from django.db.models import Q
from datetime import datetime
from zoneinfo import ZoneInfo
from .models import Task, TaskAssignment, TaskCompletion


def _date_from_request(request):
    d = request.GET.get('date') or request.POST.get('date')
    if d:
        try:
            return datetime.strptime(d, '%Y-%m-%d').date()
        except ValueError:
            pass
    # 默认使用 Asia/Shanghai 日期作为“今天”
    return datetime.now(ZoneInfo('Asia/Shanghai')).date()


@require_GET
@login_required
def daily_tasks_view(request):
    date = _date_from_request(request)
    assigned_ids = list(TaskAssignment.objects.filter(date=date).values_list('task_id', flat=True))
    base_qs = Task.objects.filter(active=True)
    qs = base_qs.filter(Q(daily=True) | Q(id__in=assigned_ids)).order_by('id') if assigned_ids else base_qs.filter(Q(daily=True)).order_by('id')
    completed_ids = set(TaskCompletion.objects.filter(user=request.user, date=date).values_list('task_id', flat=True))
    items = [{
        'id': t.id,
        'title': t.title,
        'points': t.points,
        'target': float(t.target),
        'daily': t.daily,
        'date': str(date),
        'done': t.id in completed_ids,
        'progress': 1 if t.id in completed_ids else 0
    } for t in qs]
    return JsonResponse(items, safe=False)


@require_GET
@login_required
def today_tasks_view(request):
    return daily_tasks_view(request)


@csrf_exempt
@require_POST
@login_required
def complete_task_view(request, task_id: int):
    date = _date_from_request(request)
    task = Task.objects.filter(id=task_id, active=True).first()
    if not task:
        return JsonResponse({'success': False, 'message': '任务不存在或未启用'}, status=404)
    obj, created = TaskCompletion.objects.get_or_create(user=request.user, task=task, date=date)
    if created:
        try:
            from rewards.utils import award_points
            award_points(request.user, task.points, 'task_complete', task_id)
        except Exception:
            pass
    return JsonResponse({'success': True, 'date': str(date), 'task_id': task_id, 'awarded': created})
